﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Store;
using System.Diagnostics.CodeAnalysis;
using System.IO;

namespace Steve.Lucene
{
    [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
    public sealed class ByteArrayIndexOutput : IndexOutput
    {
        MemoryStream _stream;
        Action<byte[]> _putValue;

        public ByteArrayIndexOutput(byte[] data, Action<byte[]> putValue)
        {
            if (putValue == null) throw new ArgumentNullException("putValue");

            _putValue = putValue;

            if (data == null) data = new byte[] { };

            _stream = new MemoryStream();
            _stream.Write(data, 0, data.Length);
            _stream.Position = 0;
        }


        public override void Close()
        {
            Flush();
        }

        public override void Flush()
        {
            _putValue(_stream.ToArray());
        }

        public override long GetFilePointer()
        {
            return _stream.Position;
        }

        public override long Length()
        {
            return _stream.Length;
        }

        public override void Seek(long pos)
        {
            _stream.Seek(pos, SeekOrigin.Begin);
        }

        public override void WriteByte(byte b)
        {
            _stream.WriteByte(b);
        }

        public override void WriteBytes(byte[] b, int offset, int length)
        {
            _stream.Write(b, offset, length);
        }
    }
}
